package model.code;

import model.code.line.Line;
import model.code.line.LineList;
import model.code.line.SingleLine;
import observer.Copiable;
import util.ASUtil;

import java.io.Serializable;

/**
 * This class is a superclass for objects that can be expressed as a fixed-length array of {@link LineList}.
 *
 * @author Neil Dickson
 */
public class Rowable implements Copiable<Rowable>, Serializable {
	protected	SingleLine[]	strings;

	public static final Rowable AUTHORS_DUMMY = new Rowable(1,null,CodeFileChunk.LOCATION_AUTHORS,0);
	public static final Rowable SEE_ALSO_DUMMY = new Rowable(1,null,CodeFileChunk.LOCATION_SEE_ALSO,0);

	public Rowable(int size,CodeFileChunk parent,int locationType,int row) {
		strings = new SingleLine[size];
		if (getClass()==Rowable.class) {
			for (int i=0;i<size;++i) {
				strings[i] = new SingleLine(Line.EMPTY_CHAR_ARRAY,parent,locationType,(row<<16)+i);
			}
		}
	}
	public Rowable(SingleLine[] lines) {
		this.strings = lines;
	}

	public SingleLine[] getStrings() {
		return strings;
	}

	public int getSize() {
		return strings.length;
	}

	public void setLocation(CodeFileChunk parent, int row) {
		for (SingleLine string : strings) {
			string.setLocation(parent, string.getLocationType(), (string.getLocationIndex()&0xFFFF) + (row<<16));
		}
	}

	/**
	 * This should be overridden by all subclasses.  The subclasses must return an object of their own class.
	 * @param parent	the parent code chunk for the copy
	 * @param row		the new row index for the copy
	 * @return a new Rowable that is a copy of this one
	 */
	public Rowable copy(CodeFileChunk parent,int row) {
		SingleLine[] newStrings = new SingleLine[strings.length];
		for (int i=0;i<strings.length;++i) {
			newStrings[i] = new SingleLine(ASUtil.subCharArray(strings[i].getText(),0,strings[i].length()),parent,(row<<16)+i);
		}
		return new Rowable(newStrings);
	}

	/**
	 * @return a new Rowable that is a copy of this one
	 */
	public Rowable copy() {
		return copy(strings[0].getParent(),strings[0].getLocationIndex()>>>16);
	}

	public String toString() {
		return strings[0].toString();
	}

	public Rowable copy(CodeFileChunk parent, int row, String[] defaults) {
		Rowable that = copy(parent,row);
		for (int i=0;i<that.strings.length && i<defaults.length;++i) {
			that.strings[i].replaceAll(defaults[i]);
		}
		return that;
	}
}
